package com.magic.auth.service.impl;

import com.magic.auth.client.UserClient;
import com.magic.auth.config.JwtProperties;
import com.magic.auth.service.AuthService;
import com.magic.common.pojo.UserInfo;
import com.magic.common.utils.JwtUtils;
import com.magic.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author lan.jianyuan
 * @create 2021-01-31-23:54
 */
@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private UserClient userClient;
    
    @Autowired
    private JwtProperties properties;
    
    public String authentication(String username, String password) {
        
        try {
            // 调用微服务，执行查询
            User user = this.userClient.queryUser(username, password);
            
            // 如果查询结果为null，则直接返回null
            if (user == null) {
                return null;
            }
            
            // 如果有查询结果，则生成token
            return JwtUtils.generateToken(new UserInfo(user.getId(), user.getUsername()),
                    properties.getPrivateKey(), properties.getExpire());
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
